<?php

class App_Model_DbTable_Article_Threads extends Ext_Db_Table  
{  
    /** Table name */  
    protected $_name = 'article_threads';
    
    public function get($articleId)
    {
        $articleId = intval($articleId);
        $row = $this->fetchRow(" id = '".$articleId."' ");
        if (!$row) {
            //throw new Exception("Count not find row $id");
            return "";
        }
        return $row->toArray();
    }
    
    public function add($inputArray)
    {
        $row = array (
            'tagId'             => $inputArray['tagId'],
            'articleId'         => $inputArray['articleId'],
        );
        try {
            // 插入数据行并返回插入的行数
            $rows_affected = $this->insert($row);
            $id = $this->getAdapter()->lastInsertId();
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        
        return $id;
    }
    
    public function addTags($tags, $articleId)
    {
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" articleId = ? ", $articleId);
        $row = $this->delete($safe);
        
        $_tableTag = new App_Model_DbTable_Tag();
        
        $words_array = explode(';', $tags);
        for($i=0;$i<count($words_array);$i++)
        {
            $word = $words_array[$i];
            $word = trim($word);
            if(!$word)
            {
                continue;
            }
            elseif(strlen($word)>60)
            {
                continue;
            }
            else
            {
                $inputArray = array(
                    'tagName'             => $word,
                    'createTime'     => time(),
                );            
                $tagId = $_tableTag->add($inputArray);
                
                $row = array(
                    'tagId'         => $tagId,
                    'articleId'     => $articleId,
                );
                $this->add($row);
            }
        }
        
        
    }
    
    public function getTagCount($tagId)
    {
        $db = $this->getAdapter();
        $select = $db->select();
        $select
            ->from($this->_name, array(
               Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN => 'COUNT(*)'
            ))
            ->where('tagId = :tagId')
            ;
        $params = array('tagId' => $tagId);
        $select->bind($params);
        
        return $select;
    }
    
    public function getTagList($tagId)
    {
        $db = $this->getAdapter();
        $select = $db->select();
        $select
            ->from($this->_name, "articleId")
            ->order('id DESC')
            ->where('tagId = :tagId')
            ;
        $params = array('tagId' => $tagId);
        $select->bind($params);
        
        return $select;
    }
    
}  

